blog

Home / DeveloperSection / Blogs / Difference between Singleton class and Static class

Difference between Singleton class and Static class

Manish Kumar1738 02-Mar-2017

Static class

Static class in like the normal class the feature of static class is that we can make object of static class and it contain only static members. This is also knowns as sealed class means we cannot inherit it into the child class.

Static class can have only one constructor without parameter, we cannot create parameterize constructor because to pass value of constructor we need to create object and we cannot create object of static class.

 Advantages-

It provides guarantee that object cannot be created.

It can have only one constructor without any parameter.

Let us understand with an example-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
                                
namespace ConsoleApplication10
{
   
    publicstaticclassMyMath
    {
        publicstaticfloat PI = 3.14f;
        publicstaticint cube(int n) { return n * n * n; }
    }
    publicclassA
    {
        publicvoid function()
        {
            Console.WriteLine("class A");
        }
    }
    classTestMyMath
    {
        publicstaticvoid Main(string[] args)
        {
            Console.WriteLine("Value of PI is: "+ MyMath.PI);
            Console.WriteLine("Cube of 3 is:"+ MyMath.cube(3));
            //MyMath obj = new MyMath();//error
            A obj = newA();
            obj.function();
           
 
        }
    } 
  
}

 

Difference between Singleton class and Static class



Singleton

 

This pattern involves a single class which is responsible to create an object


while making sure that only single object gets created. It just says that you


define only one instance and provide global access to it.



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
namespace SingleTonSample
{
    sealed class SingleTon
    {
        private static SingleTon single = new SingleTon();
        public static SingleTon Instance 
        {
            get { return single; } 
        }
        private SingleTon(){ }
        public void PrintMe()
        {
            Console.WriteLine("Singleton Class Testing");
        }
    }
}


You can visit these helpful related post.


What is a singleton in C#?


Updated 17-Mar-2018

Leave Comment

Comments

Liked By